package priv.mill.base;
import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

public class MybatisUtil {

	private static final String MYBATIS_CONFIG_XML = "mybatis-config.xml";
	private static final Logger logger = Logger.getLogger(MybatisUtil.class);

	public interface SessionHandler{
		void handler(SqlSession session);
	}
	
	public static void exec(SessionHandler handler) throws IOException {
		String resource = MYBATIS_CONFIG_XML;
		InputStream inputStream = 
				Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory =
				new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			handler.handler(session);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
}
